package com.example.demo.controller;

import com.example.demo.*;
import com.example.demo.repository.AutoMessageHandler;
import com.example.demo.service.AdjudeMethod;
import com.example.demo.service.SQLInterface;
import com.example.demo.service.SQLData;
import com.normalClasses.eye.*;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.jdbc.core.RowMapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Slf4j
@RestController
public class MainController {
    @Autowired
    private AutoMessageHandler messageHandler;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SQLInterface sql;

    @Autowired
    private SQLData sql_data;

    @Autowired
    private Log_Exit_timeline timeline;

    @Autowired
    private AdjudeMethod adjude_method;


    @RequestMapping("getNicknameList/{sum_number_str}")
    public void getNicknameList(@PathVariable(value = "sum_number_str") String sum_number_str, HttpServletRequest request, HttpServletResponse response) throws IOException {
        cross_domain_ajax(response);
        //解析string类型的参数
        int sum_number;
        try {
            sum_number = Integer.valueOf(sum_number_str).intValue();
        } catch (NumberFormatException e) {
            // TODO: handle exception
            log.info(LogUtil.logSpec("Visited getNicknameList/{sum_number} Failed, parameter conversion is not correct", 8));
            JSONObject resJsonObject = new JSONObject();
            resJsonObject.put("res_status", false);
            resJsonObject.put("res_describe", "url参数传递并不正确");
            PrintWriter out = response.getWriter();
            out.print(resJsonObject);
            out.flush();
            out.close();
            return;
        }
        //规定while执行的最大循环
        final int MaxLoopNum = 1000;
        int sumLoopNum = 0;
        while (true) {
            Map<String, String> maplist = sql_data.transmit_nickname_headimg_list(sum_number);
            if (maplist != null) {
                //定义内部类
                class nickurl {
                    public String url;
                    public String nickname;

                    public nickurl(String nickname, String url) {
                        // TODO Auto-generated constructor stub
                        this.url = url;
                        this.nickname = nickname;
                    }
                }
                nickurl[] nickurl = new nickurl[maplist.size()];
                //生成json数组
                Set<String> set = maplist.keySet();
                int index_num = 0;
                for (String keyString : set) {
                    //遍历map
                    nickurl[index_num] = new nickurl(keyString, maplist.get(keyString));
                    index_num++;
                }
                JSONObject resJsonObject = new JSONObject();
                resJsonObject.put("res_status", true);//将返回状态恢复
                String nickString = JSON.toJSONString(nickurl);//先将对象数组转换成字符串
                JSONArray res_source = JSON.parseArray(nickString);//再将字符串转换成json数组
                resJsonObject.put("res_source", res_source);
                log.info(LogUtil.logSpec("Visited once t_nickname_userimg"));
                PrintWriter out = response.getWriter();
                out.print(resJsonObject);
                out.flush();
                out.close();
                return;
            } else {
                sumLoopNum++;
                if (sumLoopNum >= MaxLoopNum) {
                    JSONObject resJsonObject = new JSONObject();
                    log.warn(LogUtil.logSpec("the t_nickname_userimg is Empty", 8));
                    resJsonObject.put("res_status", false);
                    resJsonObject.put("res_describe", "数据库并未剩余的昵称和头像供选择");
                    PrintWriter out = response.getWriter();
                    out.print(resJsonObject);
                    out.flush();
                    out.close();
                    return;
                }
            }
        }
    }


    @RequestMapping("sendNickname")
    public void sendNickname(HttpServletRequest request, HttpServletResponse response) throws IOException {
        cross_domain_ajax(response);
        String ipString = request.getRemoteAddr();
        log.info(LogUtil.logSpec(ipString + "visited once sendNickname interface"));
        //System.out.println(request.getParameter("cookie")+request.getParameter("nickname"));
        messageHandler.Auto_storage_nickname(request.getParameter("cookie"), request.getParameter("nickname"));
        //若不写返回流，在ajax处就会执行error，虽然success和error函数并没有实际的业务执行，但是还是为了标准起见
        PrintWriter out = response.getWriter();
        JSONObject aJsonObject = new JSONObject();
        aJsonObject.put("status", true);
        out.print(aJsonObject);
        out.flush();
        out.close();
    }


    @RequestMapping("check_nickname_chosen/{cookie}")
    public void check_nickname_chosen(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "cookie") String cookie) throws IOException {
        cross_domain_ajax(response);
        String ipString = request.getRemoteAddr();
        log.info(LogUtil.logSpec(ipString + "visited once check_nickname_chosen interface"));
        PrintWriter out = response.getWriter();
        if (!messageHandler.Auto_check_nickname(cookie)) {
            JSONObject msg = new JSONObject();
            msg.put("res_data", true);
            out.print(msg);
            out.flush();
            out.close();
        } else {
            JSONObject msg = new JSONObject();
            msg.put("res_data", false);
            msg.put("res_describe", "所选用户已经选择了昵称和头像");
            out.print(msg);
            out.flush();
            out.close();
        }
    }

    private void cross_domain_ajax(HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        /* 设置响应头允许ajax跨域访问 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星号表示所有的异域请求都可以接受， */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
    }


    @RequestMapping("hello")
    public String hello(String fame) {
        System.out.println("hello访问成功！");

        List user1 = (List) jdbcTemplate.queryForList("select * from peopletimeline where `username` = '0p11p5' and `pointtype` = 0 and `status`='true'");
        List user2 = (List) jdbcTemplate.queryForList("select * from peopletimeline where `username` = '0p11p5' and `pointtype` = 1 and `status`='true'");
        String timeout = "";
        String timelogin = "";
        if (user1.size() > 0 && user2.size() > 0) {
            Map tip1 = (Map) user1.get(0);
            Map tip2 = (Map) user2.get(0);
            timeout = (String) tip1.get("timepoint");
            timelogin = (String) tip2.get("timepoint");
            timeout = timeout.substring(0, 10);
            timelogin = timelogin.substring(0, 10);
        }
        Time time = new Time();
        return time.time(Long.parseLong(timelogin), Long.parseLong(timeout));
    }


    @RequestMapping("indexlogin")
    public void indexlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username_rem = "username";
        String password_rem = "password";
        String loginstatus_rem = "loginstatus";
        // TODO Auto-generated method stub
        //response.setContentType("text/html;charset=utf-8");
        cross_domain_ajax(response);
        //获取get或者post的参数值并打印
        String ipString = request.getRemoteAddr();
        log.info(LogUtil.logSpec(ipString + "visited indexlogin interface"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (this.sql.judge_people_exist(username, password) == 1) {
            log.info(LogUtil.logSpec(username + "Landing successfully"));//输出log
            sql.storage_ip(username, ipString);//对成功用户存储ip
            UserManagement user = this.sql.getPeople(username, password);//将用户属性从数据库读取到内存
            sql.storage_cookiestatus(user.getCookievalue(), username);//存储cookie
            sql.storage_login_time(username);//存储登入时间
            String status = user.getLoginstatus(), status1 = "false";
            if (status.equals(status1)) {
                log.info(LogUtil.logSpec(username + "perform login status modification"));
                //更改登陆状态
                this.sql.change_loginstatus(username, "true");
            } else if (!(status.equals(status1))) {
                log.warn(LogUtil.logSpec(username + "preempt the same account being used"));
                //用此cookie占据主导，抢占
                sql.substitude_people(user.getCookievalue());
            }
            PrintWriter out = response.getWriter();
            String s = JSON.toJSONString(user);
            //System.out.println(s);
            JSONObject a = JSON.parseObject(s);
            a.put("login", true);
            //将json对象不需要的键值移除
            a.remove(username_rem);
            a.remove(password_rem);
            a.remove(loginstatus_rem);
            //System.out.println(a);
            //返回值给小程序
            out.print(a);
            out.flush();
            out.close();
        } else if (this.sql.judge_people_exist(username, password) == 0) {
            JSONObject message = new JSONObject();
            message.put("login", false);
            log.warn(LogUtil.logSpec(ipString + " login failed !"));
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        }
    }


    @RequestMapping("indexregister")
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cross_domain_ajax(response);
        //获取get或者post的参数值并打印
        String ipString = request.getRemoteAddr();
        log.info(LogUtil.logSpec(ipString + "visited once registered interface"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        //进行注册逻辑的书写，进入分支
        if (this.sql.judge_people_exist(username) == 0) {
            log.info(LogUtil.logSpec(username + ",This user does not exist, you can register"));
            this.sql.register_people(username, password, email);
            log.info(LogUtil.logSpec(username + ",This user registered successfully"));
            String cookiepool = "jngiergnh4i539rDSNFWEUFHWERng45gwjlkufx9w8ixgADWEUFBWEUFty85ngo9w48hg9208726t5b109thjnxuiwmbity4773o492jfumze8oq9gu03rg9h83qrq3q2yrtgzf14dfevVWNVWRIBVKHUR3gcnmnugjit8476gmklpoi60931qawszxdefcvrbgyh";
            String cookieValue = "";
            int strnumber = cookiepool.length();
            for (int i = 0; i < 28; i++) {
                cookieValue += cookiepool.charAt((int) (Math.random() * strnumber));
            }
            log.info(LogUtil.logSpec(username + ",This user got successfully"));
            //内含四个操作
            this.sql.register_login(username, ipString, cookieValue);
            log.info(LogUtil.logSpec(username + ",This user successfully logged in"));
            PrintWriter out = response.getWriter();
            JSONObject aaa = new JSONObject();
            aaa.put("cookiename", "user");
            aaa.put("cookietime", 3);
            aaa.put("cookievalue", cookieValue);
            aaa.put("register", true);
            //System.out.println(aaa);
            //返回值给小程序
            out.print(aaa);
            out.flush();
            out.close();
        } else if (this.sql.judge_people_exist(username) == 1) {
            JSONObject message = new JSONObject();
            message.put("register", false);
            log.warn(LogUtil.logSpec(ipString + "this account" + username + "registered, failed to register"));
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        }
    }

    @RequestMapping("test1")
    public void contextLoads() {
        String sql = "select * from peopleright";

        List<TestUser> userList = (List<TestUser>) jdbcTemplate.query(sql, new RowMapper<TestUser>() {
            @Override
            public TestUser mapRow(ResultSet rs, int rowNum) throws SQLException {
                TestUser user = new TestUser();
                user.setName(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                System.out.println(rowNum);
                return user;
            }

        });

        System.out.println("查询成功");
        String s = JSON.toJSONString(userList);
        System.out.println(s);
        for (TestUser user : userList) {
            System.out.println("id = " + " , name = " + user.getName() + " , password = " + user.getPassword());
        }
        String sql1 = "select * from peopleright where `username`='0p11p5'";

        TestUser user1 = jdbcTemplate.queryForObject(sql1, new RowMapper<TestUser>() {
            @Override
            public TestUser mapRow(ResultSet arg0, int arg1) throws SQLException {
                TestUser user = new TestUser();
                user.setName(arg0.getString("username"));
                user.setPassword(arg0.getString("password"));
                System.out.println(arg1);
                return user;

            }
        });

        System.out.println(user1.getName() + user1.getPassword());
    }


    @RequestMapping("test2")
    public String test() {
        System.out.println(new Date().getTime());

        System.out.println(new Date().getTime());
        return "true";
    }

    @RequestMapping("test3")
    public String test1() {
        monitor_res_obj user = new monitor_res_obj("0p11p92p8", 0, 0);
        try {
            AutoRealTimeMonitoring.monitoring_message.push(user);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "true";
    }

    //@RequestMapping("judge_web_environment_cookie")
//public void judge_web_environment_cookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // response.setContentType("application/json;charset=utf-8");
    /* 设置响应头允许ajax跨域访问 */
    //response.setHeader("Access-Control-Allow-Origin", "*");  
    /* 星号表示所有的异域请求都可以接受， */
    //response.setHeader("Access-Control-Allow-Methods", "GET,POST");
    //获取get或者post的参数值并打印
    //String cookie = request.getParameter("cookie");
    //因限于ajax的发送特性，加以限制
    //if(cookie!=null||cookie!=""){
    //log.info(LogUtil.logSpec(cookie+"执行了检查");
    //创建消息json
//    JSONObject message = new JSONObject();
//    if(this.sql.check_cookiestatus(cookie)) {
//    	//picture pic=new picture(this.sql.load_img("1", "1"));
//    	//String s = JSON.toJSONString(pic);
//    	//message =JSON.parseObject(s);
//    	//message.put("pass", "true");
//    	//激活定时消息提示功能
//    	this.sql.activation_socketmessage(cookie);
//    }
//    else message.put("pass", "false");
//    PrintWriter out=response.getWriter();   
//    //返回值给客户端    
//    out.print(message);
//    out.flush();
//    out.close();
//    }
    //}
    @RequestMapping("judge_cookie_status/{requestfilename}")
    public void judge_cookie_status(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "requestfilename") String requestfilename) throws ServletException, IOException {
        // TODO Auto-generated method stub
        cross_domain_ajax(response);
        //获取get或者post的参数值并打印
        String cookie = request.getParameter("cookie");
        //判断url参数格式是否正确
        if (requestfilename != null || requestfilename != "") {
            String ipString = request.getRemoteAddr();
            log.info(LogUtil.logSpec(ipString + "and" + requestfilename + " visited judge_cookie_status", 6));
            //因限于ajax的发送特性，加以限制
            if (cookie != null || cookie != "") {
                log.info(LogUtil.logSpec(cookie + "checked"));
                //创建消息json
                JSONObject message = new JSONObject();
                //判断数据库是否有此cookie的相关信息
                if (this.sql.check_cookiestatus(cookie)) {
                    message.put("pass", true);
                    message.put("describe", "cookie状态正常");
                    //每次检查cookie的时候均需要激活此条定时任务的权限
                    sql.activation_socketmessage(cookie);
                } else {
                    message.put("pass", false);
                    message.put("describe", "cookie状态并不正常胡或不正确");
                }
                PrintWriter out = response.getWriter();
                //返回值给客户端
                out.print(message);
                out.flush();
                out.close();
            }
            //分支原因
            JSONObject message = new JSONObject();
            message.put("describe", "并未正确传递参数cookie");
            message.put("pass", false);
            PrintWriter out = response.getWriter();
            //返回值给客户端
            out.print(message);
            out.flush();
            out.close();
        } else {
            String ipString = request.getRemoteAddr();
            JSONObject message = new JSONObject();
            message.put("describe", "并未正确传递参数");
            message.put("pass", false);
            PrintWriter out = response.getWriter();
            //返回值给客户端
            out.print(message);
            log.warn(LogUtil.logSpec(ipString + "visited judge_cookie_status failed"));
            out.flush();
            out.close();
        }
    }

    @RequestMapping("Update_logtime/{cookie}")
    public void Update_logtime(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "cookie") String cookie) throws IOException {
        cross_domain_ajax(response);
        String ipString = request.getRemoteAddr();
        log.warn(LogUtil.logSpec(ipString + "visited Update_logtime"));//记录ip行为
        //当前时间戳
        long now_time = new Date().getTime();
        JSONObject message = new JSONObject();
        message.put("pass", timeline.Updatelogtime(cookie, String.valueOf(now_time)));
        PrintWriter out = response.getWriter();
        //返回值给客户端
        out.print(message);
        out.flush();
        out.close();
    }

    @RequestMapping("Update_exitime/{cookie}")
    public void Update_exitime(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "cookie") String cookie) throws IOException {
        cross_domain_ajax(response);
        String ipString = request.getRemoteAddr();
        log.warn(LogUtil.logSpec(ipString + "visited Update_exitime"));//记录ip行为
        //当前时间戳
        long now_time = new Date().getTime();
        JSONObject message = new JSONObject();
        message.put("pass", timeline.Updateexitime(cookie, String.valueOf(now_time)));
        PrintWriter out = response.getWriter();
        //返回值给客户端
        out.print(message);
        out.flush();
        out.close();
    }

    @RequestMapping("test/lrc")
    public String testJsonObject() {
        String keyword1 = "C 语言教程";
        String keyword2 = "C 简介";
        List t_runoob_contents1 = (List) jdbcTemplate.queryForList("SELECT * FROM `t_runoob_contents` WHERE keyword = '" + keyword1 + "'");
        List t_runoob_contents2 = (List) jdbcTemplate.queryForList("SELECT * FROM `t_runoob_contents` WHERE keyword = '" + keyword2 + "'");
        Map con1 = (Map) t_runoob_contents1.get(0);
        Map con2 = (Map) t_runoob_contents2.get(0);
        Key_word_similar test = new Key_word_similar((String) con1.get("main_text_content"), (String) con2.get("main_text_content"));
        return test.getRes_data() + "***";
    }

    @RequestMapping("arbitration_process")
    public void arbitration_process(HttpServletRequest request, HttpServletResponse response) throws IOException {
        cross_domain_ajax(response);
        //获取get或者post的参数值
        String adjude_obj = request.getParameter("adjude_obj");
        String username = request.getParameter("username");
        String arbitration = request.getParameter("arbitration");
        String id = request.getParameter("get_in_ID");
        //执行主体函数，裁决
        adjude_method.change_adjude_obj(username, adjude_obj, arbitration, id);
        //必须符合ajax要求
        PrintWriter out = response.getWriter();
        JSONObject message = new JSONObject();
        message.put("res", true);
        //返回值给客户端
        out.print(message);
        out.flush();
        out.close();
    }


    //@Scheduled(fixedRate = 60*1000)
    @RequestMapping("test_0")
    public void SystemExamination(String name) throws FileNotFoundException, ParseException {

//  String log1 = "log.log";
//  String log2 = "D:/log.log";
//  String[] usernames = messageHandler.Auto_find_username();
//  FileManipulation.getNewLogPart(log2,log1);
//  for(int i=0;i<usernames.length;i++){
//    System.out.println(test.getLoginBehaviors(usernames[i],log1));
//  }
//  log.info(LogUtil.logSpec("fen ge line");
// return  	messageHandler.Auto_operation_notice("fUVd4UiUgdyF1B7j5BUxFt88ehRx");
// System.out.println(test.getCookieBehaviors("0p11p92p8","log.log"));
// LinkedList<userBehavior> behaviors = analyzer.usernameBehavior4(name,log2);
// for(userBehavior item: behaviors) {
//  System.out.println(item.getInformation()+"**");
// }
// System.out.println(test.getErrorBehaviors(log1));
// System.out.println(test.getWarningBehaviors(log1));
// System.out.println(test.getDebugBehaviors(log1));
// message resMessage=message::new

        monitor_res_obj msg = new monitor_res_obj("", 23, 0);
        //为消息处理主体添加信息
        msg.appendMessage("定时器1出现了错误，建议立刻处理，否则危害系统" + "\n");
        msg.appendMessage("定时器5出现了错误，建议立刻处理，否则危害系统" + "\n");
        try {
            AutoRealTimeMonitoring.monitoring_message.push(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

//   return ((Lambda_fun)(cookie,msg)->{
//	   String username=messageHandler.Auto_getusername(cookie);
//	   msg.setTitle("您的回馈");
//	   msg.setContent(spyder.get_user_notification(username));
//	   return JSON.toJSONString(msg);
//	   }).getUserReportFeedback("fUVd4UiUgdyF1B7j5BUxFt88ehRx",new message());
    }
}
